package controller;

import core.BlogException;
import core.Uzivatel;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import model.UzivatelModel;

/**
 * Managed Beana pouzita pro Login uzivatelu a drzeni stavu uzivatele
 * @author vojta
 */

@ManagedBean(name="LoginBean")
@SessionScoped
public class LoginBean implements Serializable {
    
    private Uzivatel loggedUzivatel = null;
    private String login, heslo;

    public String getHeslo() {
        return heslo;
    }

    public void setHeslo(String heslo) {
        this.heslo = heslo;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }            
    
    public Uzivatel getLoggedUzivatel() {
        return loggedUzivatel;
    }

    public void setLoggedUzivatel(Uzivatel loggedUzivatel) {
        this.loggedUzivatel = loggedUzivatel;
    }
            
    /**
     * Overi jestli je uzivatel validni
     * @return 
     */
    public String validateUzivatel() {
        try {
            UzivatelModel model = new UzivatelModel();
            
            Uzivatel u = new Uzivatel();
            u.setHeslo(heslo);
            u.setLogin(login);
                        
            if ((u = model.validateUzivate(u)) != null) {
                loggedUzivatel = u;
                return "index";
            } else {
                loggedUzivatel = null;
                FacesContext.getCurrentInstance().addMessage("pridatU:heslo1", new FacesMessage("Chyba: Spatne jmeno/heslo!"));
                return "index";
            }
            
        } catch (BlogException ex) {            
            System.err.println("Spadlo to... pri overovani uzivatel...hups");
            return "login";
        }

    }
    
    /**
     * Odhlasi uzivatele
     * @return 
     */
    public String logout() {
        loggedUzivatel = null;
        login = null;
        heslo = null;
        
        return "index";
    }

}
